package qscript;
import grafica.GPlot;
import grafica.GPoint;
import grafica.GPointsArray;

import org.qscript.Script;
import org.qscript.Result;
import org.qscript.errors.EvaluationException;
import org.qscript.errors.SyntaxException;

import processing.core.PApplet;


public class Polar001 extends PApplet {

	GPlot plot;
	GPointsArray points;

	String ft = "(sin($t) * sqrt(abs(cos($t))))/(sin($t) + 1.4) - 2*sin($t) + 2";
	float tMin = 0, tMax = TWO_PI, tDelta = 0.01f;
	float gcx, gcy;
	
	public void setup(){
		size(640,400);
		plot = new GPlot(this);
		plot.setPos(66, 73);
		plot.setOuterDim(300,300);
		points = calcPoints(ft, tMin, tMax, tDelta);
		plot.setPoints(points);
		plot.setBgColor(color(255,200,200));
		plot.getXAxis().setAxisLabelText("X");
		plot.getYAxis().setAxisLabelText("Y");
		
//		plot.activateCentering();
		plot.activatePanning();
		plot.activateZooming();
		
		printPlotDetails(plot);
	}

	public void printPlotDetails(GPlot p){
		float[] pos = p.getPos();
		println("Position   " + pos[0] + "  " + pos[1] );
		float[] odim = p.getOuterDim();
		println("Outer dim  " + odim[0] + "  " + odim[1] );
		float[] idim = p.getDim();
		println("Inner dim  " + idim[0] + "  " + idim[1] );
		
		float[] mar = p.getMar();
		println("Margins    " + mar[0] + "  " + mar[1]+ "  " + mar[2]+ "  " + mar[3] );
		gcx = pos[0] + idim[0]/2 + mar[1];
		gcy = pos[1] + idim[1]/2 + mar[2];
		
	}
	
	public void keyTyped(){
		if(key == 'q'){
			points = calcPoints("1-cos($t)", tMin, tMax, tDelta);
			plot.setPoints(points);
		}
		if(key == '+'){
			plot.zoom(1.1f, gcx, gcy);
		}
		if(key == '-'){
			plot.zoom(1/1.1f, gcx, gcy);
		}
	}
	
	
	public GPointsArray calcPoints(String expr, float t0, float t1, float dt){
		GPoint[] points;
		Script script = new Script(expr);
		
		try {
			script.parse_();
		} catch (SyntaxException e) {
			println("Syntax " + e.getMessage());
			return null;
		}
		points = new GPoint[1 + round((t1 - t0)/dt)];
		float t = t0;
		for(int i = 0; i < points.length; i++){
			t = t0 + i * dt;
			script.storeVariable("$t", t);
			float r=0;
			try {
				Result result = script.evaluate_();
				r = result.answer.toFloat_();
			} catch (EvaluationException e) {
				println("Eval " + e.getMessage());
				return null;
			}
			points[i] = new GPoint(r*cos(t), r*sin(t));
		}
		return new GPointsArray(points);
	}

	public void draw(){
		background(255);
		plot.beginDraw();
		plot.drawBackground();
		plot.drawBox();
		plot.drawXAxis();
		plot.drawYAxis();
	    plot.drawTopAxis();
	    plot.drawRightAxis();
		plot.drawLines();
		plot.endDraw();		 
		fill(0);
		text( "" + mouseX + " , " + mouseY, 20, height - 20);
		
	}
}
